﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using WiMo.Games.Drawables;
using WiMo.Games.Silverlight.GameEngine.Drawables;
using System.Windows.Media.Imaging;
using System.Windows.Resources;

namespace WiMo.Games.Silverlight.GameEngine
{
    public class ContentManager : IContentManager
    {
        public ContentManager(IGameEngine engine)
        {
            Engine = engine;

            AssetFactory = engine.AssetFactory;
        }

        private ITexture LoadTexture(string name)
        {
            var assembly = Engine.Game.GetType().Assembly;

            var assemblyName = assembly.FullName.Substring(0, assembly.FullName.IndexOf(','));

            var contentPath = string.Format(@"{0};component/{1}/{2}", assemblyName, ContentLocation, name);
            var contentUri = new Uri(contentPath, UriKind.Relative);

            var sr = Application.GetResourceStream(contentUri);
            if (sr == null)
                return null;

            var bitmap = new BitmapImage();
            bitmap.SetSource(sr.Stream);
            sr.Stream.Dispose();

            return new Texture { TextureInformation = bitmap };
        }

        public IAssetFactory AssetFactory { get; private set; }

        public string ContentLocation { get; set; }

        public WiMo.Games.Audio.IGameAudio LoadAudio(string name)
        {
            var gameAudio = Engine.AudioManager.LoadSound(name);

            return gameAudio;
        }

        public ISpriteImage LoadImage(string name)
        {
            var imageAsset = AssetFactory.CreateSpriteImage();
            imageAsset.Load(this, name);

            return imageAsset;
        }

        public IGameEngine Engine { get; set; }

        public ITexture GetTexture(string name)
        {
            var texture = LoadTexture(name);
            if (texture != null)
                return texture;

            texture = LoadTexture(String.Format("{0}.png", name));
            if (texture != null)
                return texture;

            texture = LoadTexture(String.Format("{0}.bmp", name));
            if (texture != null)
                return texture;

            throw new NullReferenceException(String.Format("Could not find asset with name: {0}, {0}.png,{0}.bmp.\r\n\r\nName of asset is case sensitive, also for consistency make sure your extensions is in lower case.", name));
        }

        public string GetFullPath(string name)
        {
            throw new NotImplementedException();
        }

        public ISpriteFont GetFont(string name)
        {
            return new SpriteFont();
        }

        public void Dispose()
        {

        }
    }
}
